<?php

define("breakfast","breakfast");
define("breakfastDisplay","早餐");
define("lunch","lunch");
define("lunchDisplay","午餐");
define("dinner","dinner");
define("dinnerDisplay","晚餐");
define("orderReservePrefix", "R");
define("noticeTitle","预订单");
define("noticeFormat",
"联  系 人：%s
联系电话 ：%s
预订人数 ：%s
预订类型 ：%s
桌位/包间：%s
预订时间 ：%s
备     注：%s");
class store {
	
	public static function getStoreDistrictArray($parentId,$order="CONVERT( name USING gbk )",$orderBy="asc",$start = 0, $limit =25) {
		$arr = store::StoreDistrictArray($parentId,$order,$orderBy,$start, $limit);
		
		$resultArr = $arr["arr"];
		if($resultArr){
			Output::instance()->module('store', 'store_district')->object($resultArr);
		}else{
			Output::instance()->resultCode(code_success);
		}
		
	}
	public static function getPickupStoreDistrict($parentId,$order,$orderBy) {
		$resultArr = self::getPickupStoreDistrictArray($parentId,$order,$orderBy);
		if ($resultArr) {
			Output::instance()->object($resultArr);
		} else {
			Output::instance()->resultCode(code_success);
		}
	}

	public static function getPickupStoreDistrictArray($parentId,$order,$orderBy) {
		$arr = store::StoreDistrictArray($parentId,$order,$orderBy,'NULL', NULL);
		return $arr["arr"];
	}
	
	public static function getStoreDistrict($districtCategoryId,$parentId,$order="CONVERT( name USING gbk )",$orderBy="asc",$start = 0, $limit =25) {
		
		$arr = store::StoreDistrictArray($districtCategoryId,$parentId,$order,$orderBy,$start, $limit);
		
		$resultArr = $arr["arr"];
		$result["name"] = $arr["name"];		
		$result["pId"] = $arr["pId"];
		
		if($resultArr){
			$result["districts"] = $resultArr;
			$result["districtsTotal"] = store::StoreDistrictCount($districtCategoryId,$parentId,$order="id",$orderBy="asc",$start = 0, $limit =25);
		} else {
			$result["districtsTotal"] = 0;
		}
		
		Output::instance()->module('store', 'store_district')->object($result);
	}
	
	private static function StoreDistrictArray($parentId,$order,$orderBy,$start, $limit){
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		
		$StoreDistrictModel = M("store_district");
		if(isset($parentId)){
			$pc["id"] = array('eq',$parentId);
			$pc["fromCustomerId"] = array('eq',$customerId);
		}else{
			$pc["parentId"] = array('exp','is NULL');
			$pc["fromCustomerId"] = array('eq',$customerId);
		}
		$parentDistrict = $StoreDistrictModel->where($pc)->find();
//		if (!$parentDistrict) {
//			Output::instance()->resultCode(code_store_district_not_exist);
//			return NULL;
//		}
		
		$parentId = $parentDistrict["id"];
		
		$result["name"] = $parentDistrict['name'];
		$result["pId"] = $parentDistrict['id'];
		
		$condition['parentId'] = array('eq',$parentId);
		$condition['deleted'] = array('eq',0);
		$condition['fromCustomerId'] = array('eq',$customerId);
		
		
		if($start.'' == 'NULL'){
			$arr = $StoreDistrictModel->where($condition)->field('id,name,leaf')->order("$order $orderBy")->select();
		}else{
			$arr = $StoreDistrictModel->where($condition)->field('id,name,leaf')->order("$order $orderBy")->limit("$start,$limit")->select();
		}
		Session::switchCustomer($customerId);
		
		$result["arr"] = $arr;
		return $result;
	}
	private static function StoreDistrictCount($districtCategoryId,$parentId,$order="id",$orderBy="asc",$start = 0, $limit =25){
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		
		$StoreDistrictModel = M("store_district");
		if(isset($parentId)){
				$pc["id"] = array('eq',$parentId);
				$pc["fromCustomerId"] = array('eq',$customerId);
				$pc["districtCategoryId"] = array('eq',$districtCategoryId);
			}else{
				$pc["parentId"] = array('exp','is NULL');
				$pc["fromCustomerId"] = array('eq',$customerId);
				$pc["districtCategoryId"] = array('eq',$districtCategoryId);
			}
		
// 		$parentDistrict = $StoreDistrictModel->where("id=$parentId")->find();
		$parentDistrict = $StoreDistrictModel->where($pc)->find();
		if (!$parentDistrict) {
			Output::instance()->resultCode(code_store_district_not_exist);
			return NULL;
		}
		
		$parentId = $parentDistrict["id"];
		
		$result["name"] = $parentDistrict['name'];
		$condition['parentId'] = array('eq',$parentId);
		$condition['deleted'] = array('eq',0);
		$condition['fromCustomerId'] = array('eq',$customerId);
		$condition["districtCategoryId"] = array('eq',$districtCategoryId);
		
		$count  =$StoreDistrictModel->where($condition)->count();
		
		Session::switchCustomer($customerId);
		return $count;
	}
	
	public static function getStoreList($districtId,$order="id",$orderBy="asc",$start = 0, $limit =25){
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		
		$StoreModel = M("store");
		$condition['store.districtId'] = array('eq',$districtId);
		$condition['store.deleted'] = array('eq',0);
		
		
		$districtName = $StoreModel->alias("store")->where($condition)
		->join("wx_store_district dis ON dis.id=store.districtId")
		->field("dis.name name")->find();
		
		$result["name"] = $districtName['name'];
		
		$DistrictModel = M("store_district");
		$category = $DistrictModel->alias("dis")->where("dis.id = $districtId")
		->join("wx_store_district_category category ON dis.districtCategoryId=category.id")
		->field("category.id,category.typeId")->find();
		
		if ($category["typeId"] == type_dish) {
			$arr = $StoreModel->alias("store")->where($condition)
			->join('wx_store_extend_base base ON store.id=base.storeId')
			->join('wx_store_extend_dish dish ON base.id=dish.storeId')
			->field("store.*,base.onlineReserve,base.onlineOrder,base.onlineTakeout,base.reserveWebPageId,base.reserveWebPageName,base.email,base.feyinDeviceNo,dish.lunchTime,dish.dinnerTime")
			->order("$order $orderBy")->limit("$start,$limit")->select();
			
			$count = $StoreModel->alias("store")->where($condition)
			->join('wx_store_extend_base base ON store.id=base.storeId')
			->join('wx_store_extend_dish dish ON base.id=dish.storeId')
			->count();
			
		} else {
			
			$con['districtId'] = array('eq',$districtId);
			$con['deleted'] = array('eq',0);
			
			$arr = $StoreModel->where($con)->order("$order $orderBy")->limit("$start,$limit")->select();
			$count = $StoreModel->where($con)->count();
		}
		
		
		$result["categoryType"] = $category["typeId"];
		$result["categoryId"] = $category["id"];
		$result["total"] = $count;
		$result["results"] = $arr;
		
		Session::switchCustomer($customerId);
		Output::instance()->module('store', 'store')->object($result);
	}
	
	public static function getPickupStoreList($districtId, $order, $orderBy){
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		
		$StoreDistModel = M("store_district");
		$dist = $StoreDistModel->where("id=$districtId")->find();
		if ($dist == false ) {
			Output::instance()->resultCode(code_store_district_not_exist);
			return;			
		}
		
		$StoreModel = M("store");
		$con['districtId'] = $districtId;
		$con['deleted'] = 0;
		$con['isPickUp'] = 1;
		
		$arr = $StoreModel->where($con)->order("$order $orderBy")->select();
		if ($arr) {
			Output::instance()->object($arr);
			Session::switchCustomer($customerId);
			return;
		}
		$code = $dist['code'];
		$where["code"] = array('LIKE', "$code%");
		$sqlCode = $StoreDistModel->field("id")->where($where)->select(false);
		$condition['_string'] = "districtId IN ( $sqlCode )";
		$condition['deleted'] = 0;
		$condition['isPickUp'] = 1;
		$arr = $StoreModel->where($condition)->order("$order $orderBy")->select();
		echo $StoreModel->getLastSql();
		Session::switchCustomer($customerId);
// 		Log::write($StoreModel->getLastSql());
		if ($arr) {
			Output::instance()->object($arr);
		} else {
			Output::instance()->resultCode();
		}
	}
	
	public static function reserveSelNum($id) {
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		
		$StoreModel = M("store_extend_dish");
		$condition['storeId'] = array('eq',$id);
		$condition['deleted'] = array('eq',0);
		
		$result = $StoreModel->where($condition)->field("storeId,breakfastTime,lunchTime,dinnerTime")->find();
		
		$dates = array();
		$startDate = date('Y-m-d');
		for($i = 0 ; $i <= 29 ; $i++){
			$temDate = $i*24*60*60 + strtotime(date('Y-m-d',strtotime($startDate)));
			$temArray = array(
					"dateTime"=>date('Y-m-d',$temDate)
			);
			array_push($dates,$temArray);
		}
		$result["dates"] = $dates;
		
		$times = array();
		$temArray = array("timeId"=>lunch,"timeDisplay"=>lunchDisplay);
		array_push($times,$temArray);
		
		$temArray = array("timeId"=>dinner,"timeDisplay"=>dinnerDisplay);
		array_push($times,$temArray);
		
		$result["times"] = $times;
		
		Output::instance()->module('store', 'store_reserve_sel_num')->object($result);
	}
	
	public static function reserve($id,$personCount,$reserveType,$reserveDate,$userName) {
		
		
		$userInfo = get_UserInfo_by_fromUserName($userName);
		if ($userInfo) {
			$fullName= $userInfo[user_full_name];
			$phone = $userInfo[user_phone];
		}
		
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		
		$StoreModel = M("store");
		$StoreResourceBaseModel = M("store_resource_base");
		
		$StoreResourceDishModel = M("store_resource_dish");
		$StoreReserve = M("store_reserve");
		$StoreExtendBase = M("store_extend_base");
		$StoreExtendDish = M("store_extend_dish");
		
		$condition['store.id'] = array('eq',$id);
		$condition['store.deleted'] = array('eq',0);
		
		$result = $StoreModel->alias("store")->where($condition)
		->join('wx_store_extend_base base ON store.id=base.storeId')
		->join('wx_store_extend_dish dish ON dish.id=dish.storeId')
		->join('wx_'.$customerId.'_web_page page ON base.reserveWebPageId=page.id')
		->field("store.id,base.email,base.feyinDeviceNo,dish.breakfastTime,dish.lunchTime,dish.dinnerTime,page.content storeTip")->find();
		
		if($userInfo){
			$src['fromCustomerId'] = array('eq',$customerId);
			$src['fromUserName'] = array('eq',$userName);
// 			$src['storeId'] = array('eq',$id);
			$reserveCount = $StoreReserve->where($src)->count();
// 			echo $StoreReserve->getLastSql();
			
			if($reserveCount > 0){
				$result["reserveCount"] = $reserveCount;
			}
		}
		
		///
		$sr['reserveType'] = array('eq',$reserveType);
		$sr['storeId'] = array('eq',$id);
		$sr['reserveDate'] = $reserveDate;
		$ids = $StoreReserve->where($sr)->field('storeResourceBaseId')->select();
		
		if($ids){
			$storeResourceBaseId = array();
			foreach ($ids as $stdId){
				array_push($storeResourceBaseId,$stdId['storeResourceBaseId']);
			}
			$rc['base.id'] = array('not in',$storeResourceBaseId);
		}
		$rc['base.storeId'] = array('eq',$id);
		$rc['base.deleted'] = array('eq',0);
		$rc['dish.minSize'] = array('elt',$personCount);
		$rc['dish.maxSize'] = array(array('egt',$personCount),array('exp','is NULL'), 'or') ;
		
		$resources = $StoreResourceBaseModel->alias("base")->where($rc)
		->join('wx_store_resource_dish dish ON base.id=dish.storeResourceBaseId')
		->field("base.id,base.name")->select();
// 		echo $StoreResourceBaseModel->getLastSql();
		//$resources = $StoreResourceDishModel->where($rc)->field('id,name')->select();
		
		if($resources){
			$result["resources"] = $resources;
		} else {
			$result["resources"] = '';
		}
		
		$sedrc['storeId'] = array('eq',$id);
		$storeExtendDish = $StoreExtendDish->where($sedrc)->find();
		
// 		$startTime = '';
// 		$endTime = '';
		
// 		if($reserveType == lunch ){
// 			$startTime = (((int)substr($storeExtendDish['lunchTime'], 0,2)) + 1)+"";
// 			$endTime = (((int)substr($storeExtendDish['dinnerTime'], 0,2)) - 1)+"";
// 		}else if($reserveType == dinner ){
// 			$startTime = (((int)substr($storeExtendDish['dinnerTime'], 0,2)) + 1)+"";
// 			$endTime = 23;
// 		}
		
		$reservehtimes = array();
		for($i=10;$i <=23;$i++){
			$temTime = $i;
			$temArray = array("time"=>$temTime);
			array_push($reservehtimes,$temArray);
		}
		for($i=0;$i <10;$i++){
			$temTime = "0".$i;
			$temArray = array("time"=>$temTime);
			array_push($reservehtimes,$temArray);
		}
		
		$reserveitimes = array();
		for($i=0;$i <=11;$i++){
			$temTime='';
			if($i<2){
				$temTime = "0".$i*5;
			}else{
				$temTime = $i*5;
			}
			
			$temArray = array("time"=>$temTime);
			array_push($reserveitimes,$temArray);
		}
		
		$result["reservehtimes"] = $reservehtimes;
		$result["reserveitimes"] = $reserveitimes;
		
		$result["fullName"] = $fullName;
		$result["phone"] = $phone;
		Output::instance()->module('store', 'store_reserve')->object($result);
	}
	
	
	public static function addReserve($storeId,$userName,$fullName,$phone,$reserveTime,$reserveDate,$reserveType,$personCount,$remark=NULL,$storeResourceBaseId=NULL){
		
		if ($fullName != NULL) {
			
			$userInfo = get_UserInfo_by_fromUserName($userName);
			if(!$userInfo){
				create_UserInfo_by_fromUserName($userName);
			}
			
			update_UserInfo_by_message($userName, $fullName, user_full_name);
			update_UserInfo_by_message($userName, $phone, user_phone);
		}
		
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		
		$StoreReserveModel = M("store_reserve");
		
		$data["storeId"] = $storeId;
		$data["fromCustomerId"] = fromCustomerId;
		$data["fromUserName"] = $userName;
		$data["reserveTime"] = $reserveTime;
		$data["reserveDate"] = $reserveDate;
		$data["reserveType"] = $reserveType;
		$data["personCount"] = $personCount;
		$createTime = date("Y-m-d H:i:s");
		$data["createTime"] = $createTime;
		$data["updateTime"] = $createTime;
		$data["remark"] = $remark;
		$data["storeResourceBaseId"] = $storeResourceBaseId;
		$result = $StoreReserveModel->add($data);
		if ($result) {
			$sn = orderReservePrefix . date("Ymd") . $result;
			$StoreReserveModel->where("id=$result")->setField("serialNumber", $sn);
			
			$StoreExtendBase = M("store_extend_base");
			$extend = $StoreExtendBase->alias("extend")->where("extend.storeId=$storeId")
				->join("wx_store_resource_base res ON res.storeId=extend.storeId")
				->join("wx_store store ON store.id = extend.storeId")
				->field("store.name as storeName, extend.email,extend.emailNoticeFormat,extend.feyinDeviceNo,extend.feyinPrintFormat")->find();
			
			$StoreRes = M("store_resource_base");
			$resName = $StoreRes->where("id=$storeResourceBaseId")->field("name")->find();
			$reserveTypeDisplay = dinnerDisplay;
			if ($reserveType == lunch) {
				$reserveTypeDisplay = lunchDisplay;
			}
			if ($extend["feyinDeviceNo"] != NULL || $extend["email"] != NULL) {
				$msgContent = sprintf(noticeFormat, $fullName, $phone, $personCount, $reserveTypeDisplay, $resName["name"], 
						$reserveTime, $remark);
				if ($extend["feyinDeviceNo"] != NULL) {
					$msg = str_ireplace("{serialNumber}", $sn, $extend["feyinPrintFormat"]);
					$msg = str_ireplace("{storeName}", $extend["storeName"], $msg);
					$msg = str_ireplace("{createTime}", $createTime, $msg);
					$msg = str_ireplace("{content}", $msgContent, $msg);

					store::feyinPrint($extend["feyinDeviceNo"], $msg);
				}
				if ( $extend["email"] != NULL) {
					$msg = str_ireplace("{serialNumber}", $sn, $extend["emailNoticeFormat"]);
					$msg = str_ireplace("{storeName}", $extend["storeName"], $msg);
					$msg = str_ireplace("{createTime}", $createTime, $msg);
					$msg = str_ireplace("{content}", $msgContent, $msg);
					
					$title =  noticeTitle. $sn;
					$mailResult = SendMail($extend["email"],$title,$msg,null,EMAIL_BCCADRESS); //直接调用发送即可
					if(!$mailResult){
						Log::write('store reserve send mail failure :'.$mailResult);
					}
				}
			}
			Output::instance()->object($result);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
	}
	
	private function feyinPrint($feyinDeviceNo, $msg) {
		$arrDeviceNo = explode(",", $feyinDeviceNo);
		foreach ($arrDeviceNo as $deviceNo) {
			$freeMessage = array(
					'msgDetail' => $msg,
					'deviceNo' => $deviceNo,
			);
			Feyin::sendFreeMessage($freeMessage);
		}
	}
	
	public static function getStoreReserveOrders($storeId,$userName,$start = 0, $limit =10,$order="updateTime",$orderBy="desc"){
// 		$uniUserInfo = get_UniUserInfo_by_userName($userName);
		
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		
		$StoreReserve = M("store_reserve");
		$StoreResourceDishModel = M("store_resource_dish");
		$StoreResourceBaseModel = M("store_resource_base");
		
		$condition['reserve.fromUserName'] = array('eq',$userName);
		$condition['reserve.fromCustomerId'] = array('eq',$customerId);
// 			$condition['store.storeId'] = array('eq',$storeId);
			//->order("$order $orderBy")->limit("$start,$limit")
		$reserveOrders = $StoreReserve->alias("reserve")->where($condition)
		->join('wx_store_resource_Base res ON reserve.storeResourceBaseId=res.id')
		->join('wx_store store ON reserve.storeId=store.id')
		->field("reserve.*,res.id resId,res.name resName,store.name sName,store.address sAddress")
		->limit("$start,$limit")
		->order("$order $orderBy")->select();
		
		if($reserveOrders){
			$count = $StoreReserve->alias("reserve")->where($condition)
			->join('wx_store_resource_Base res ON reserve.storeResourceBaseId=res.id')
			->join('wx_store store ON reserve.storeId=store.id')
			->count();
		
			$result["orders"] = $reserveOrders;
			$result["ordersTotal"] = $count;
		}else{
			$result["ordersTotal"] = 0;
		}
			
		
		Output::instance()->module('store', 'store_reserve_order')->object($result);
		
	}
	public static function getStoreReserveOrderDetail($id,$userName){
		$result = new stdClass();
		$userInfo = get_UserInfo_by_fromUserName($userName);
		
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		
		$StoreReserve = M("store_reserve");
		$StoreResourceDishModel = M("store_resource_dish");
		$StoreResourceBaseModel = M("store_resource_base");
		if($userInfo){
			// 			$unid = $uniUserInfo['uniUserId'];
			// 			$condition['reserve.id'] = array('eq',$id);
			// 			$result = $StoreReserve->alias("reserve")->where($condition)
			// 			->join('wx_store_resource_Base res ON reserve.storeResourceBaseId=res.id')
			// 			->join('wx_store store ON reserve.storeId=store.id')
			// 			->field("reserve.*,res.id resId,res.name resName,store.name sName,store.address sAddress,store.picUrl sPicUrl,store.phone sPhone")
			// 			->find();
			
			// 			if($result){
			// 				$result["fullName"] = $uniUserInfo['fullName'];
			// 			}
				
			$result = store::getStoreReserveOrder($id,$userName,$userInfo['fullName']);
			
		}

		Session::switchCustomer($customerId);
		Output::instance()->module('store', 'store_reserve_order_detail')->object($result);
	}
	
	public static function getStoreReserveOrder($id,$fromUserName,$fullName){
// 		$result = array();
// 		$uniUserInfo = get_UniUserInfo_by_uniUserId($unid);
		
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		
		$StoreReserve = M("store_reserve");
		$StoreResourceDishModel = M("store_resource_dish");
		$StoreResourceBaseModel = M("store_resource_base");
		
		$condition['reserve.id'] = array('eq',$id);
		$result = $StoreReserve->alias("reserve")->where($condition)
		->join('wx_store_resource_Base res ON reserve.storeResourceBaseId=res.id')
		->join('wx_store store ON reserve.storeId=store.id')
		->field("reserve.*,res.id resId,res.name resName,store.name sName,store.address sAddress,store.picUrl sPicUrl,store.phone sPhone")
		->find();
		
		Session::switchCustomer($customerId);
		if($result){
			$result["fullName"] = $fullName;
		}else{
			$result =  null;
		}
		
		return $result;
	}
	/**
	 * 根据门店内存储的文章url获取文章内容
	 * Enter description here ...
	 * @param unknown_type $url
	 */
	public  static  function  getArticleWebPageByUrl($url){
		$customerId = Session::$user["customerId"];
		$userName=Session::$user["userName"];
		if($url==''){
			return '';
		}
		if (preg_match ('/id%22:(\d+)%7D/', $url, $m)) 
		{ 
			if(count($m)>0){
				$id=$m[1];
			}
		} 
		$condition['id']=array('eq',$id);
		$article=M('web_page');
		$result =$article->where($condition)->find();
		Session::switchCustomer($customerId);
		if($result){
			return $result;
		}else{
			return "";
		}
	}
	public static function getStoreDetail($id){
		$customerId = Session::$user["customerId"];
		$userName=Session::$user["userName"];
		Session::switchCustomer(0);
		$serviceList = M("store_service_list");
		$Store = M("store");
		$condition['id'] = array('eq',$id);
		$condition['deleted'] = array('eq',0);
		
		$result =$Store->where($condition)->find();
		$result['picUrl1']=json_decode($result['picUrl1'],true);
		$result['serviceList']=$serviceList->alias("a")
			->join("inner join wx_store_service b on a.serviceId =b.id")
			->where("a.storeId=".$result['id'])->field("b.id,b.name")->select();
		$tplId=$result['tplId'];
		//兼容之前的
		if($tplId==NULL || $tplId==""){
			$tplId="store_detail";
		}
		switch ($tplId){
			case 'store_detail_button':
				$callUrl=C('SERVER_HOST') . "call.html?customerId=$customerId&userName=$userName&module=drive&method=getSchoolList&storeId=" . $id;
				break;
		}
		Session::switchCustomer($customerId);
		//根据url提取文章内容
		$webPage=self::getArticleWebPageByUrl($result['url']);
		if($result){
			$result['callUrl']=$callUrl;
			$result['webPage']=$webPage;
			Output::instance()->module('store', $tplId)->object($result);
		}else{
			Output::instance()->resultCode(code_success,'抱歉,此门店不存在');
		}
	}

	public function baiduMap($id){
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		$Store = M("store");
		Session::switchCustomer($customerId);
		$result = $Store->where("id=$id")->field("id,longitude,latitude")->find();
		Output::instance()->module('store', 'baidumap')->object($result);
	}

	//门店列表
	public function allStore(){
		$cid=Session::$user['customerId'];
		Session::switchCustomer(0);
		$storeService = M("store_service");
		Session::switchCustomer($cid);
		$result['serviceList'] = $storeService->where("cid=$cid")->field("id,name")->select();
		Output::instance()->module("store","allStore")->object($result);
	}
	public function storeList($search,$latitude,$longitude,$province,$city,$serviceId,$juli,$order,$start=0,$limit=20){
		!$order?$order='juli asc':"";
		$cid=Session::$user['customerId'];
		Session::switchCustomer(0);
		$storeModule = M("store");
		Session::switchCustomer($cid);
		$start = $start*$limit;
		$where="a.deleted = 0 and customerId=$cid ";
		if($province&&$city){
			$where.=" and ((a.province='$province' and a.city='$city') or a.address like '%".$province.$city."%')";
		}else if($province){
            $where.=" and ((a.province='$province') or a.address like '%".$province."%')";
        }
		$search?$where.=" and (a.name like '%$search%' or a.phone like '%$search%' or a.address like '%$search%')":"";
		if($juli||$serviceId||$order=='juli asc'){
			$juli?$condition = " d.juli<$juli":"";
			$serviceId?$condition = " find_in_set($serviceId,serviceId)":"";
			!strlen($condition)?$condition="true":"";
			$sql = "select * from (select a.id,a.picUrl,a.name,a.phone,a.address,a.province,a.city,a.country,a.latitude,a.longitude,".
				"GROUP_CONCAT(c. NAME) AS serviceName,GROUP_CONCAT(c. id) AS serviceId,ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(($latitude * PI() / 180 - a.latitude * PI() / 180) / 2),2) + COS($latitude * PI() / 180) * COS(a.latitude * PI() / 180) * POW(SIN(($longitude * PI() / 180 - a.longitude * PI() / 180) / 2),2))) ,2) AS juli".
				" from wx_store a left join wx_store_service_list b ON a.id = b.storeId left join wx_store_service c ON b.serviceId = c.id where ".$where." group by a.id order by $order ) d where ".$condition ." limit $start,$limit";
			$arr = $storeModule->query($sql);

		}else{
			$arr = $storeModule->alias("a")
				->join("wx_store_service_list b ON a.id = b.storeId")
				->join("wx_store_service c ON b.serviceId = c.id")
				->where($where)
				->field("a.id,a.picUrl,a.name,a.phone,a.address,a.province,a.city,a.country,a.latitude,a.longitude,
            GROUP_CONCAT(c. NAME) AS serviceName,ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(($latitude * PI() / 180 - a.latitude * PI() / 180) / 2),2) + COS($latitude * PI() / 180) * COS(a.latitude * PI() / 180) * POW(SIN(($longitude * PI() / 180 - a.longitude * PI() / 180) / 2),2))),2) AS juli")
				->limit($start,$limit)
				->order("$order")
				->group("a.id")
				->select();
		}
		if($arr){
			foreach($arr as $key=>$value){
				if($value['serviceName']){
					$arr[$key]['serviceName'] = explode(",",$value['serviceName']);
				}
			}
			if($juli||$serviceId||$order=='juli asc'){
				$juli?$condition = " d.juli<$juli":"";
				$serviceId?$condition = " find_in_set($serviceId,serviceId)":"";
				strlen($condition)?$condition="true":"";
				$sql = "select * from (select a.id,".
					"GROUP_CONCAT(c. NAME) AS serviceName,GROUP_CONCAT(c. id) AS serviceId,ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(($latitude * PI() / 180 - a.latitude * PI() / 180) / 2),2) + COS($latitude * PI() / 180) * COS(a.latitude * PI() / 180) * POW(SIN(($longitude * PI() / 180 - a.longitude * PI() / 180) / 2),2))) ,2) AS juli".
					" from wx_store a left join wx_store_service_list b ON a.id = b.storeId left join wx_store_service c ON b.serviceId = c.id where ".$where." group by a.id) d where ".$condition;
				$count = $storeModule->query($sql);
			}else{
				$count = $storeModule->alias("a")
					->join("wx_store_service_list b ON a.id = b.storeId")
					->join("wx_store_service c ON b.serviceId = c.id")
					->where($where)
					->group("a.id")
					->select();

			}
			$count = count($count);
			Output::instance()->objArray($arr,$count);
		}else{
			Output::instance()->resultCode();
		}
	}
}